﻿﻿﻿﻿/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/*  description :常用功能函数
 *  author :hetanhong
 *  create :2014-6-17
 *  update : 2014-8-28

 */

// 添加遮罩
window.mark = function () {
    var mark = d3.select("body").append("div").classed("mark", true);
    mark.style("width", "100%").style("height", "100%").style("top", "0px").style("left", "0px")
        .style("background", "black").style("opacity", "0")
        .style("z-index", 99).style("position", "fixed");
    mark.transition().duration(100).style("opacity", 0.6);
    return mark;
};
// 添加spinner
window.progress = function () {
    var progress = d3.select("body").append("div").classed("progress", true).style({
        left: "50%",
        top: "45%",
        "z-index": 99,
        position: "absolute"
    });
    var opts = {
        lines: 18, // The number of lines to draw
        length: 10, // The length of each line
        width: 3, // The line thickness
        radius: 10, // The radius of the inner circle
        corners: 1, // Corner roundness (0..1)
        rotate: 0, // The rotation offset
        direction: 1, // 1: clockwise, -1: counterclockwise
        color: '#ffe', // #rgb or #rrggbb or array of colors
        speed: 1, // Rounds per second
        trail: 60, // Afterglow percentage
        shadow: false, // Whether to render a shadow
        hwaccel: false, // Whether to use hardware acceleration
        className: 'spinner', // The CSS class to assign to the spinner
        zIndex: 200000, // The z-index (defaults to 2000000000)
        top: 'auto', // Top position relative to parent in px
        left: 'auto' // Left position relative to parent in px
    };
    var spinner = new Spinner(opts).spin(progress.node());
    return progress;
};
//  注销账户 ，退出应用
var LoginOut = function () {
    var url = serverURL + "cmcp/doLoginOut";
    var info = window.localStorage.info;
    var self = null
    if (info) {
        info = JSON.parse(info) || null;
        self = {
            appId: info.appid || null,
            devicetype: info.deviceType || null,
            userId: info.user_id || null,
            channalId: info.channel_id || null
        };
    }
    fastgoPushNotification.registered = false;
    window.localStorage.removeItem("Lcatch");
    PostCP(url, self, function (dat) {
        console.log(dat);
        navigator.ca.close();
        //window.closeView();
		window.localStorage.removeItem("sid");
		window.plugins.getIntent.closeView([]);
    }, function () {
        console.log("error");
        navigator.ca.close();
        window.localStorage.removeItem("sid");
        //window.closeView();
        window.plugins.getIntent.closeView([]);
    }, function () {
    	navigator.ca.close();
        window.localStorage.removeItem("sid");
        window.plugins.getIntent.closeView([]);
    }, function () {
    	navigator.ca.close();
        window.localStorage.removeItem("sid");
        window.plugins.getIntent.closeView([]);
    });
    setTimeout(function () {
        //window.closeView();
    	navigator.ca.close();
        window.localStorage.removeItem("sid");
        window.plugins.getIntent.closeView([]);
    }, 1000);
};

// 截取一定长度的字符串
// str :源字符串 length :截取长度 ，postfix 截取后字符串末尾填补字符 ，默认为...
var handleLongString = function (str, length, postfix) {
    if (str == null) {
        return null;
    }
    length = 120;
    if (str.length < length)
        return str;
    if (!postfix) {
        postfix = "..."
    }
    var theRealLength = 0;
    var theReturnStr = "";
    for (var i = 0; i < str.length; i++) {
        theRealLength++
        if (theRealLength <= length) {
            theReturnStr = theReturnStr + str[i] || null;
        } else {
            theReturnStr = theReturnStr + postfix || null;
            break;
        }
        if (str[i].match(/[^\x00-\xff]/ig) != null) {
            theRealLength++;
        }
    }
    return theReturnStr;
};
var handleLongString_ = function (str, length, postfix) {
    if (str == null) {
        return null;
    }
    if (str.length < length)
        return str;
    if (!postfix) {
        postfix = "..."
    }
    length = 146;
    var theRealLength = 0;
    var theReturnStr = "";
    for (var i = 0; i < str.length; i++) {
        theRealLength++
        if (theRealLength <= length) {
            theReturnStr = theReturnStr + str[i] || null;
        } else {
            theReturnStr = theReturnStr + postfix || null;
            break;
        }
        if (str[i].match(/[^\x00-\xff]/ig) != null) {
            theRealLength++;
        }
    }
    return theReturnStr;
};
var _substr = function (str) {
    if (!str)
        return "";
    if (str.length < 35)
        return str;
    return str.substr(0, 35) + ".."

}

var _substr2 = function (str,length) {
	if(length==null){
		length = 35;
	}
    if (!str)
        return "";
    if (str.length <= length)
        return str;
    return str.substr(0, length) + "..."
}
//  封装Ajax ，前后台交互
// url 请求地址 ，data 参数 ，suc 成功回调函数 ，err 失败回调函数 ,beforeSend：请求前执行动作，complete：请求完成执行动作
var showType = "none";
var PostCP = function (url, data, suc, err, beforeSend, complete) {
    console.log(url);
    console.log(data);
    var xtechAth=window.localStorage.getItem("xtechAth");
    //Alert("一期token==>"+xtechAth);
    $.ajax({
        url: url,
        dataType: "json",
        type: "POST",
        data: JSON.stringify(data),
        contentType: "application/json",
        beforeSend: function (xhr) {
        	xhr.setRequestHeader('XTECH_ATH', xtechAth);
            if (beforeSend) {
                beforeSend();
                return;
            }
            if (showType == "none") {
                if (isMobile.Android())
                    navigator.notification.activityStart("政府OA系统", "请等待...");
            }
            showType = "true"
        },
        complete: function () {
            if (complete) {
                complete();
                return;
            }
            showType = "false"
            setTimeout(function () {
                if (showType == "false") {
                    showType = "none";
                    if (isMobile.Android())
                        navigator.notification.activityStop();
                }
            }, 250);

            ;
        },
        success: function (a, b, c) {
            if (suc)
                suc(a, b, c);
        },
        error: function (a, b, c) {
            if (err){
                err(a, b, c);
            }
        }

    });
};
var PostOAC = function (url, data, suc, err, beforeSend, complete) {
    var sid=window.localStorage.getItem("sid");
	jQuery.support.cors = true;
    $.ajax({
        url: url,
        dataType: "json",
        type: "POST",
        data: JSON.stringify(data),
        contentType: "application/json",
        beforeSend: function (xhr) {
        xhr.setRequestHeader('sid', sid);
            if (beforeSend) {
                beforeSend();
                return;
            }
            if (showType == "none") {
                if (isMobile.Android())
                    navigator.notification.activityStart("政府OA系统", "请等待...");
            }
            showType = "true"
        },
        complete: function () {
            if (complete) {
                complete();
                return;
            }
            showType = "false"
            setTimeout(function () {
                if (showType == "false") {
                    showType = "none";
                    if (isMobile.Android())
                        navigator.notification.activityStop();
                }
            }, 250);

            ;
        },
        success: function (a, b, c) {
            if (suc)
                suc(a, b, c);
        },
        error: function (a, b, c) {
            if (err)
                err(a, b, c);
        }

    });
};
var GETOAC = function (url,suc, err, beforeSend, complete) {
    var sid=window.localStorage.getItem("sid");
   　	jQuery.support.cors = true;
    $.ajax({
        url: url,
        dataType: "json",
        type: "GET",
        contentType: "application/json",
        beforeSend: function (xhr) {
        	xhr.setRequestHeader('sid', sid);
            if (beforeSend) {
                beforeSend();
                return;
            }
            if (showType == "none") {
                if (isMobile.Android())
                    navigator.notification.activityStart("政府OA系统", "请等待...");
            }
            showType = "true"
        },
        complete: function () {
            if (complete) {
                complete();
                return;
            }
            showType = "false";
            setTimeout(function () {
                if (showType == "false") {
                    showType = "none";
                    if (isMobile.Android())
                        navigator.notification.activityStop();
                }
            }, 250);
        },
        success: function (a, b, c) {
            if (suc)
                suc(a, b, c);
        },
        error: function (a, b, c) {
            if (err)
                err(a, b, c);
        }
    });
};
var PostXF = function (url, data, suc, err, beforeSend, complete) {
    console.log(url);
    console.log(data);
    $.ajax({
        url: url,
        //  dataType: "json",
        type: "POST",
        data: data,
        //  contentType: "application/json",
        beforeSend: function () {
            if (beforeSend) {
                beforeSend();
                return;
            }
            if (showType == "none") {
                if (isMobile.Android())
                    navigator.notification.activityStart("政府OA系统", "请等待...");
            }
            showType = "true"
        },
        complete: function () {
            if (complete) {
                complete();
                return;
            }
            showType = "false"
            setTimeout(function () {
                if (showType == "false") {
                    showType = "none";
                    if (isMobile.Android())
                        navigator.notification.activityStop();
                }
            }, 350);

            ;
        },
        success: function (a, b, c) {
            if (suc)
                suc(a, b, c);
        },
        error: function (a, b, c) {
            if (err)
                err(a, b, c);
        }

    });
}
// 弹出提示信息  ，一段时间后自动消失
// str 信息内容
// duration 提示内容显示时间
var Prompt = function (str, duration) {
    duration = 1000;
    var div = d3.select("body").append("div").classed("prompt", true).html(str);
    setTimeout(function () {
        div.transition().duration(duration).style("opacity", 0);
        setTimeout(function () {
            div.remove();
        }, duration);
    }, duration);
//    return div;
};
// 弹出提示信息 ，点击确定后消失 ，封装 pc端 和Android端
var Alert = function (str) {
    if (window.isMobile.Android()) {
        navigator.notification.alert(str, function () {
        }, '政府OA系统', '确定');
    }
    else {
        window.console.log(str);
    }
};
// 添加登录人员信息
var userAppend = function () {
    var userName = d3.select("body").append("div").classed("userName", true);
    var url = serverURL + "cmcp/phone/doGetUserInfo";
    PostCP(url, null, function (dat) {
        var name = dat["userName"] || "";
        var party = dat["orgName"] || "";
        var imageURL = serverURL + dat["userImg"];
        var imageName = imageURL.split("ui/")[1];
        console.log(dat);
        window.localStorage["userId"] = dat["userId"];// 2015 -1- 14 增加user_id
        window.localStorage["roleCode"] = dat["roleCode"];//2017-8-29 增加roleCode
        window.localStorage.userInfo = JSON.stringify(dat);
        d3.select(".userName").append("p").style({
            "font-size": "14px",
			"width":"130px"
        }).html(name);
		if(name.length >9){
			$(".userName").css("top","0.5%");
			$(".userName").css("height","44px");
			$(".userName").css("line-height","20px");
		}
        window.downLoad(imageURL, imageName, suc);
        function suc(URL) {
            picURL = URL;
        }
    }, function () {
        var name = "--";
        var party = "---";
        userName.append("p").style({
            "font-size": "14px"
        }).html(name);
        /*
         userName.append("p").style({
         "font-size": "10px"
         }).html(party);*/
    });

};
var init = function () {
    document.addEventListener("pause", function () {
        currentTime = new Date().getTime();
        var timer1 = setInterval(function () {
            console.log(new Date());
            var date = new Date().getTime();
            if (date - currentTime > disTime) {
                window.plugins.getIntent.startTop();
                clearInterval(timer1)
            }
        }, 60 * 1000);


    });
};
var onResume = function (Resume) {
    document.addEventListener("resume", Resume, false);

};
// 检查应用是否有更新版本
var update = function (suc, err) {
	/*var url = serverURL + "cmcp/phone/getUpdateInfo";
	window.plugins.getIntent.getVersion([], function (text) {
		var verdata = {
			userCode : window.localStorage.CA_Name,
			deviceType : "mobile",
			appVersion : text
		}
		PostCP(url,verdata,suc);
	});*/
};
var getDicts = function (suc, err) {
    var url = serverURL + "cmcp/dict/getDicts";

    PostCP(url, ["dynamic_category"], suc, err);
    return;
    var xtechAth=window.localStorage["xtechAth"];
    $.ajax({
        url: url,
        //   dataType:"json",
        beforeSend: function(xhr) {
        	xhr.setRequestHeader("XTECH_ATH",xtechAth);
        },
        success: function (dat) {
            suc(dat);
        },
        error: function () {
            if (err)
                err()
        }
    });
}
var getSeal = function (self, suc) {
    var url = serverURL + "cmcp/seal/getInfo";
    var businessId = self["businessId"];
    var businessType = self["businessType"];
    console.log(self);
    console.log(url);
    PostCP(url, self, suc, function () {
        Alert("获取错误");
    });

};
var objectJudge = function (obj) {
    if (!obj)
        return false;
    for (var name in obj) {
        if (name == "上卡标示")
            continue;
        if (obj[name] && obj[name].length)
            return true;
    }
    return false;
}
var litPaper = function () {
    navigator.notification.prompt("请输入" + String + "内容", function (result) {

        if (result.buttonIndex == 1) {
            Alert(JSON.stringify(result));
        }
    }, "政府OA系统", ["确认", "取消"], "");
};
var Edit = function (String, html, sucFun) {
    if (!isMobile.Android()) {

        var tempstr = window.prompt("请输入" + String + "内容", html);
        sucFun(tempstr);
    } else {
        navigator.notification.prompt("请输入" + String + "内容", function (result) {
            if (result.buttonIndex == 2) {
                sucFun(result.input1);
            }
        }, "政府OA系统", ["取消", "确认"], html);
    }
};
var chenge = function (value) {
    console.log(value)
}

function getURLParam(ParamName, parentSearch){
    var reg = new RegExp("(^|&)" + ParamName + "=([^&]*)(&|$)");
    var r = null;
    if (parentSearch) {
        r = decodeURI(parent.window.location.search).substr(1).match(reg);
    } else {
        r = decodeURI(window.location.search).substr(1).match(reg);
    }
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}
